package com.greendragon.service.backend.impl; 

import java.util.List;

import com.greendragon.persistence.dao.ICategoryDao;
import com.greendragon.persistence.domain.ProductCategory;
import com.greendragon.persistence.enmu.FetchOrderType;
import com.greendragon.service.backend.ICategoryBackendService;

/** 
 * @author wulibin, exceptsky@gmail.com, 2011-11-6 下午01:01:06
 * 
 */
public class ProductCategoryBackendService extends BaseBackendService<ProductCategory> implements ICategoryBackendService<ProductCategory>{
	private ICategoryDao<ProductCategory> categoryDao;
	
	@Override
	public void updateRootCategory(long cid, Long newParentCategoryId) {
		ProductCategory category = categoryDao.get(cid);
		ProductCategory newParentCategory = categoryDao.get(newParentCategoryId);
		ProductCategory oldParentCategory = category.getParentCategory();
		List<ProductCategory> oldChiladCategory  = oldParentCategory.getChildCategories();
		
		for(int i=0; i<oldChiladCategory.size(); i++){
			if(oldChiladCategory.get(i).getId() == category.getId()){
				oldChiladCategory.remove(i);
				break;
			}
		}
		
		category.setParentCategory(newParentCategory);
		newParentCategory.getChildCategories().add(category);
		
		update(category);
		update(newParentCategory);
		update(oldParentCategory);
	}
	
	@Override
	public ProductCategory getByName(String name){
		return categoryDao.getByName(name);
	}
	
	@Override
	public List<ProductCategory> getAllRootCategories(int page){
		return categoryDao.getAllRootCategories(page*pageLength, pageLength, FetchOrderType.CREATE_DESC);
	}
	
	public void setCategoryDao(ICategoryDao<ProductCategory> categoryDao) {
		this.categoryDao = categoryDao;
		this.setDao(categoryDao);
	}

}
 